package com.fishingwithme.android.ui.screens.anybitting

import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.CircleMessage
import com.fishingwithme.android.data.model.City
import com.fishingwithme.android.data.model.HarvestContent
import com.fishingwithme.android.data.model.SpotContent
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.screens.map.SideBar
import com.fishingwithme.android.ui.screens.map.SideBarItem
import com.fishingwithme.android.ui.theme.AppColors
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.AnybitingViewModel
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.delay

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AnyBittingScreen(
    navController: NavController,
    viewModel: AnybitingViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val listState = rememberLazyListState()
    val swipeRefreshState = rememberSwipeRefreshState(isRefreshing = uiState.isRefreshing)
    val context = LocalContext.current
    val barItems by remember {
        mutableStateOf(
            mutableListOf(
                SideBarItem(
                    key = "switch_city",
                    icon = R.mipmap.switch_city,
                    handler = SwitchHandler("switch_city", R.mipmap.switch_city)
                )
            )
        )
    }

    // State for city switch bottom sheet
    var showCitySwitchSheet by remember { mutableStateOf(false) }
    var searchQuery by remember { mutableStateOf("") }
    var previousSearchQuery by remember { mutableStateOf<String?>(null) }

    val locationPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val fineLocationGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: false
        val coarseLocationGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false

        if (fineLocationGranted || coarseLocationGranted) {
            viewModel.checkLocationPermission()

        }
    }

    LaunchedEffect(Unit) {
        // 检查是否需要请求权限
        val hasFineLocation = ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED

        val hasCoarseLocation = ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED

        if (!hasFineLocation && !hasCoarseLocation) {
            // 先执行权限请求
            locationPermissionLauncher.launch(
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                )
            )
        }

        viewModel.initializeLocationBasedData()
        viewModel.searchCities("")
    }

    // Trigger search when query changes (with debounce)
    LaunchedEffect(searchQuery) {

        if (previousSearchQuery != searchQuery) {
            previousSearchQuery = searchQuery
            // Debounce search to avoid too many API calls
            delay(1000)
            // Check if the query is still the same after delay
            if (searchQuery == previousSearchQuery) {
                viewModel.searchCities(searchQuery)
            }
        }
    }


    // City Switch Bottom Sheet
    if (showCitySwitchSheet) {

        val sheetState = rememberModalBottomSheetState()
        ModalBottomSheet(
            onDismissRequest = { showCitySwitchSheet = false },
            sheetState = sheetState
        ) {
            CitySwitchContent(
                currentCity = uiState.currentCityLocation.city ?: City(
                    "",
                    stringResource(R.string.unknown_city)
                ),
                searchQuery = searchQuery,
                onSearchQueryChange = { query ->
                    searchQuery = query
                },
                filteredCities = uiState.searchResults,
                isSearching = uiState.isSearching,
                onCitySelected = { city ->
                    showCitySwitchSheet = false
                    viewModel.selectCity(city)
                }
            )
        }
    }

    // Remove Scaffold and use Box directly to fill available space
    Box(modifier = Modifier.fillMaxSize()) {
        SwipeRefresh(
            state = swipeRefreshState,
            onRefresh = {
                viewModel.refreshMessages()
            },
            modifier = Modifier.fillMaxSize()
        ) {

            LazyColumn(
                state = listState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(AppDimensions.SPACING_2), // Use AppDimensions
                verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_2) // Use AppDimensions
            ) {
                // 按两个一组分组消息，实现一行两列布局
                items(uiState.messages.chunked(2)) { pair ->
                    Column(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_2) // Use AppDimensions
                        ) {
                            pair.forEach {
                                MessageCard(
                                    message = it,
                                    navController = navController,
                                    modifier = Modifier
                                        .weight(1f)
                                        .fillMaxSize()
                                )
                            }
                            // 如果只有一个项目，添加一个占位符以保持布局平衡
                            if (pair.size == 1) {
                                Spacer(modifier = Modifier.weight(1f))
                            }
                        }
                    }
                }

                if (uiState.isLoading && uiState.messages.isNotEmpty()) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(AppDimensions.SPACING_16),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }
                }

                if (!uiState.hasMoreData && uiState.messages.isNotEmpty()) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(AppDimensions.SPACING_16),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = stringResource(R.string.error_no_content),
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
            
            SideBar(
                barItems = barItems,
                onItemClick = { handler ->
                    if (handler.key == "switch_city") {
                        showCitySwitchSheet = true
                    } else if (handler.key == "show_harvest") {
                        navController.navigate(FishingNavigation.HARVEST)
                    }
                }
            )
        }

        // Show loading for initial load
        if (uiState.isLoading && uiState.messages.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        }

        // Show error message
        uiState.error?.let { error ->
            LaunchedEffect(error) {
                // You can show a snackbar here
                viewModel.clearError()
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CitySwitchContent(
    currentCity: City,
    searchQuery: String,
    onSearchQueryChange: (String) -> Unit,
    filteredCities: List<City>,
    isSearching: Boolean,
    onCitySelected: (City) -> Unit
) {

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(AppDimensions.SPACING_16)
    ) {
        // Search input
        TextField(
            value = searchQuery,
            onValueChange = onSearchQueryChange,
            label = { Text(stringResource(R.string.query_city)) },
            leadingIcon = {
                Icon(
                    imageVector = Icons.Default.Search,
                    contentDescription = "Search"
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppDimensions.SPACING_16),
            colors = TextFieldDefaults.textFieldColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            )
        )

        // Current city
        Text(
            text = stringResource(R.string.current_city) + ": ${currentCity.city ?: stringResource(R.string.unknown_city)}",
            style = MaterialTheme.typography.bodyLarge,
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_16)
        )

        // City list
        LazyColumn {
            // Show loading indicator when searching
            if (isSearching) {
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(AppDimensions.SPACING_16),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
            } else {
                items(filteredCities) { city ->
                    CityItem(
                        city = city,
                        onClick = { onCitySelected(city) }
                    )
                }

                // Show a message when search returns no results
                if (filteredCities.isEmpty()) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(AppDimensions.SPACING_16),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = stringResource(R.string.error_no_city_found),
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CityItem(
    city: City,
    onClick: () -> Unit
) {

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = AppDimensions.SPACING_2),
        onClick = onClick,
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface
        )
    ) {
        Text(
            text = city.city ?: stringResource(R.string.unknown_city),
            style = MaterialTheme.typography.bodyLarge,
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_16)
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MessageCard(
    message: CircleMessage<*>,
    navController: NavController,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            // .padding(horizontal = AppDimensions.SPACING_2, vertical = AppDimensions.SPACING_2) // Use SPACING_2
            .aspectRatio(4f / 3f),
        shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_4),
        elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2),
        onClick = {
            // 只有 NewSpotMessage 类型的卡片才执行跳转
            if (message.subtype == "EVT_N_SPOT") {
                val content = message.content as? SpotContent
                if (content != null) {
                    navController.navigate("${FishingNavigation.HOME}?id=${content.id}")
                }
            } else if (message.subtype == "EVT_SHOW_H") {
                val content = message.content as? HarvestContent
                if (content != null) {
                    navController.navigate("${FishingNavigation.SHOW}?id=${content.id}")
                }
            }
        }
    ) {
        // 移除内边距，让图片能完全布满卡片
        when (message.subtype) {
            "EVT_SHOW_H" -> {
                val content = message.content as? HarvestContent
                if (content != null) {
                    ShowHarvestMessage(content)
                } else {
                    // Fallback for when content is not properly deserialized
                    Surface(
                        modifier = Modifier.fillMaxSize(),
                        color = MaterialTheme.colorScheme.primaryContainer
                    ) {
                        Text(stringResource(R.string.error_load_failed))
                    }
                }
            }

            "EVT_N_SPOT" -> {
                val content = message.content as? SpotContent
                if (content != null) {
                    NewSpotMessage(content)
                } else {
                    // Fallback for when content is not properly deserialized
                    Surface(
                        modifier = Modifier.fillMaxSize(),
                        color = MaterialTheme.colorScheme.secondaryContainer
                    ) {
                        Text("无法加载内容")
                    }
                }
            }

            else -> {
                // Handle unknown message types
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.surfaceVariant
                ) {
                    Text("未知消息类型: ${message.subtype}")
                }
            }
        }
    }
}

@Composable
fun ShowHarvestMessage(
    content: HarvestContent,
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier
    ) {
        // 显示第一张图片作为底图
        if (content.pictures.isNotEmpty()) {
            AsyncImage(
                model = content.pictures.first(),
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )
        } else {
            // 如果没有图片，显示默认背景色
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colorScheme.primaryContainer
            ) {}
        }

        // 添加线性渐变背景层，使文字更清晰
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    brush = Brush.horizontalGradient(
                        colors = listOf(
                            AppColors.BLACK.copy(alpha = 0.5f), // rgba(15, 15, 15, 0.5)
                            Color.Transparent
                        )
                    )
                )
        ) {}

        // 在图片上层显示文字
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(AppDimensions.SPACING_16),
            contentAlignment = Alignment.BottomCenter
        ) {
            Text(
                text = stringResource(R.string.share_harvest),
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
                color = AppColors.WHITE
            )
        }
    }
}

@Composable
fun NewSpotMessage(
    content: SpotContent,
    modifier: Modifier = Modifier
) {
    Box(
        modifier = modifier
    ) {
        // 显示第一张图片作为底图
        if (content.pictures.isNotEmpty()) {
            AsyncImage(
                model = content.pictures.first(),
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )
        } else {
            // 如果没有图片，显示默认背景色
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colorScheme.secondaryContainer
            ) {}
        }

        // 添加线性渐变背景层，使文字更清晰
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    brush = Brush.horizontalGradient(
                        colors = listOf(
                            AppColors.BLACK.copy(alpha = 0.5f), // rgba(15, 15, 15, 0.5)
                            Color.Transparent
                        )
                    )
                )
        ) {}

        // 在图片上层显示文字
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(AppDimensions.SPACING_16),
            contentAlignment = Alignment.BottomCenter
        ) {
            Text(
                text = stringResource(R.string.find_new_spot),
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
                color = AppColors.WHITE
            )
        }
    }
}